/***************************************************************************
 * 文件名：FMPluginMarket
 * 功能：
 * 说明： 插件市场界面
 * -------------------------------------------------------------------------
 * 创建时间：2025/7/22 8:51:56
 * 创建人：葛浩
 * 邮箱：2094733071@qq.com
 * =========================================================================
 *
 * 修改人：   
 * 修改时间：   
 * 修改说明：   
 ***************************************************************************/
using DevExpress.XtraEditors;
using DevExpress.XtraNavBar;

using RunMethodLibrary;

using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

using Util;

namespace AuxiliaryTools
{
	public partial class FMPluginMarket : XtraForm
	{
		#region Propertys

		private string _configurationFile;

		/// <summary>
		/// 已安装引用列表
		/// </summary>
		private List<ToolModel> ToolModels = new List<ToolModel>();

		#endregion

		#region Const

		/// <summary>
		/// /已安装应用标签
		/// </summary>
		private const string c_ShowInstallAppsLabel = "已安装应用";

		/// <summary>
		/// 本地应用子项前缀
		/// </summary>
		private const string c_LocalApplication = "localNavBarItem";

		/// <summary>
		/// 服务端应用子项前缀
		/// </summary>
		private const string c_ServerApplication = "serverNavBarItem";

		#endregion

		#region Win

		public FMPluginMarket(string configurationFile)
		{
			InitializeComponent();
			_configurationFile = configurationFile;
		}

		private void FMPluginMarket_Load(object sender, EventArgs e)
		{
			InitInstallApps();

			InitToolFromServer();
		}

		#endregion

		#region Methods

		/// <summary>
		/// 初始化已安装引用列表
		/// </summary>
		private void InitInstallApps()
		{
			try
			{
				if(string.IsNullOrEmpty(_configurationFile) || !File.Exists(_configurationFile))
				{
					return;
				}

				ToolModels = AuxiliaryToolUtil.GetToolConfiguration(_configurationFile);
				if (ToolModels?.Count == 0)
				{
					return;
				}

				ShowInstallAppLabel();

				//本地应用数据
				var localApplications = ToolModels.Where(p=> p.IsLocalApplication).ToList();
				//添加至本地应用列表
				AddToNavBarGroup(localNavBarGroup, localApplications, c_LocalApplication);

				//服务端下载应用数据
				var serverTools = ToolModels.Where(p => !p.IsLocalApplication).ToList();
				//添加至服务端应用列表
				AddToNavBarGroup(serverNavBarGroup, serverTools, c_ServerApplication);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 添加至NavBarGroup中
		/// </summary>
		/// <param name="navBarGroup"></param>
		/// <param name="toolModels"></param>
		/// <param name="navBarItemPrefix"></param>
		private void AddToNavBarGroup(NavBarGroup navBarGroup,List<ToolModel> toolModels,string navBarItemPrefix)
		{
			try
			{
				if (string.IsNullOrEmpty(_configurationFile) || !File.Exists(_configurationFile))
				{
					return;
				}

				if(navBarGroup == null)
				{
					return;
				}

				for (int i = 0; i < toolModels.Count; i++) 
				{
					#region 设置基本信息

					var tool = toolModels[i];
					if (tool == null) { continue; }
					NavBarItem navBarItem = new NavBarItem();

					Font font = new System.Drawing.Font("微软雅黑", 11F);
					navBarItem.Appearance.Font = font;
					navBarItem.Appearance.Options.UseFont = true;
					navBarItem.AppearancePressed.Font = font;
					navBarItem.AppearancePressed.Options.UseFont = true;

					navBarItem.AppearanceHotTracked.Font = new System.Drawing.Font("微软雅黑", 13F);
					navBarItem.AppearanceHotTracked.Options.UseFont = true;

					navBarItem.Name = navBarItemPrefix + (i + 1).ToString();
					navBarItem.Caption = tool.Name;

					#endregion

					#region 设置图片

					string smallImageDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tool.ToolFileDir, UtilConst.SmallImage);
					if (!Directory.Exists(smallImageDir))
					{
						Directory.CreateDirectory(smallImageDir);
					}

					string smallImagePath = Path.Combine(smallImageDir,tool.ImagePath);

					if (!File.Exists(smallImagePath))
					{
						//首先从程序包的Image文件夹下获取，若不存在从主程序目录下的DefaultImage下获取
						string sourceImagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tool.ToolFileDir, UtilConst.Image, tool.ImagePath);
						if (!File.Exists(sourceImagePath))
						{
							sourceImagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, UtilConst.DefaultImage, tool.ImagePath);
						}

						if (File.Exists(sourceImagePath))
						{
							FileHelperUtil.GeneratorSizeImage(sourceImagePath, smallImagePath);
						}
					}

					navBarItem.ImageOptions.SmallImage = Image.FromFile(smallImagePath);

					#endregion

					#region 绑定事件

					//点击事件
					navBarItem.LinkClicked += (s, e) =>
					{
						try
						{
							#region 检测启动配置项

							//如果程序入口不为空，则启动对应的程序
							if (string.IsNullOrEmpty(tool.ToolFileDir) || string.IsNullOrEmpty(tool.ProgramEntrance))
							{
								return;
							}

							#endregion

							#region 执行启动程序

							//检测文件类型，判断是Exe文件还是dll
							bool isExeProgram = FileHelperUtil.IsProgramExe(tool.ProgramEntrance);

							switch (tool.StartMode)
							{
								case ProgramStartMode.IndependentThreads:
									{
										if (!isExeProgram)
										{
											MessageBox.Show($"{tool.Name}工具配置有误,请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										//检测程序入口文件是否存在
										string programPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tool.ToolFileDir, tool.ProgramEntrance);

										if (string.IsNullOrEmpty(programPath) || !File.Exists(programPath))
										{
											MessageBox.Show($"{tool.Name}工具程序入口配置有误,请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										//启动程序
										Process.Start(programPath);

										break;
									}
								case ProgramStartMode.InterfaceCall:
									{
										//从程序入口配置中解析dll文件名称、调用入口
										var list = tool.ProgramEntrance.Split(';');
										if (list == null || list.Count() == 0 || list.Length != 2)
										{
											MessageBox.Show($"{tool.Name}工具程序入口配置有误,请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										string dllFileName = list[0];
										string callClassName = list[1];

										//检测程序入口文件是否存在
										string programPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tool.ToolFileDir, dllFileName);

										if (string.IsNullOrEmpty(programPath) || !File.Exists(programPath))
										{
											MessageBox.Show($"{tool.Name}工具程序入口配置的Dll文件不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										//获取接口实例
										var IRunMethod4SingleForms = RunMethodUtil.GetExecutes(programPath, callClassName);
										if (IRunMethod4SingleForms?.Count == 0)
										{
											MessageBox.Show($"{tool.Name}调用点配置有误！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										//启动程序
										if (IRunMethod4SingleForms[0] is IRunMethod4SingleForm singleForm)
										{
											// 通过事件手动解析依赖项
											AppDomain.CurrentDomain.AssemblyResolve += (sender, argsx) =>
											{
												string dependencyPath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tool.ToolFileDir), $"{new AssemblyName(argsx.Name).Name}.dll");
												return File.Exists(dependencyPath) ? Assembly.LoadFrom(dependencyPath) : null;
											};

											if (!MainFormOption.Search2BringToFront(singleForm.FormType))
											{
												IRunMethod4SingleForms[0].Execute();
											}
										}
										break;
									}
								default:
									return;
							}

							#endregion
						}
						catch (Exception ex)
						{
							MessageBox.Show("启动工具失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
						}
					};

					#endregion

					#region 添加至组

					navBarGroup.ItemLinks.Add(navBarItem);

					#endregion
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 显示已安装应用数量
		/// </summary>
		private void ShowInstallAppLabel()
		{
			labShowInstallApps.Text = c_ShowInstallAppsLabel + (string.Format("({0})", ToolModels?.Count > 0 ? ToolModels?.Count : 0));
		}

		/// <summary>
		/// 从服务端获取可安装工具(未实现，现在测试使用)
		/// </summary>
		private void InitToolFromServer()
		{
			try
			{
				panelControl4.AutoScroll = true;
				panelControl4.AutoScrollMinSize = new Size(panelControl4.Width, panelControl4.Height);

				//测试代码
				var localApplications = ToolModels.Where(p => p.IsLocalApplication).ToList();
				if (localApplications?.Count == 0)
				{
					return;
				}

				List<CustomToolControlModel> list = new List<CustomToolControlModel>();
				localApplications.ForEach(data => list.Add(new CustomToolControlModel()
				{
					ToolName = data.Name,
					ToolDesc = data.Name + "测试显示描述信息",
				}));

				int locationY = 0;
				Size size = new Size(panelControl4.Width,panelControl4.Height);
				FMToolGroupCard fm = new FMToolGroupCard(localApplications, size, "本地安装", list);
				panelControl4.Controls.Add(fm);
				locationY += fm.Height - 20;

				FMToolGroupCard fm2 = new FMToolGroupCard(localApplications, size, "本地安装2", list);
				fm2.Location = new Point(0,locationY);
				panelControl4.Controls.Add(fm2);

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#endregion
	}
}
